﻿using System;

namespace NDBGen.Descriptors.Columns.Tokens
{
    [ColumnTokenDescriptor(HasValue = true)]
    public sealed class ForeignKeyTokenDescriptor : ColumnTokenDescriptorBase, IOrderedMetadata
    {
        private const String TOSTRING_FORMAT = "{0}{1}.{2}.{3}";
        
        public ForeignKeyTokenDescriptor() { }
        internal ForeignKeyTokenDescriptor(Table table, String columnName, String foreignKeyReference)
        {
            var column = new Column(table, columnName, DataType.None);
            this.Init(table, column, foreignKeyReference);
        }

        protected override Char Token { get { return '>'; } }

        public String ForeignKeySchema { get; private set; }
        public String ForeignKeyTable { get; private set; }
        public String ForeignKeyColumn { get; private set; }

        public override String TokenValue
        {
            get { return base.TokenValue; }
            protected set
            {
                base.TokenValue = value;
                
                var parts = value.Split('.');

                if (parts.Length != 3)
                {
                    var exmsg = String.Format("Foreign key declaration {0} for column {1} is in an invalid format. Expected {{schema}}.{{table}}.{{column}}", this.TokenValue, this.Column.Name);
                    throw new ArgumentException(exmsg, "metadataValue");
                }

                this.ForeignKeySchema = parts[0];
                this.ForeignKeyTable = parts[1];
                this.ForeignKeyColumn = parts[2];
            }
        }

        Int32 IOrderedMetadata.GenerationIndex { get { return 5; } }

        public override String ToString()
        {
            return this.InitCalled ? String.Format(TOSTRING_FORMAT, this.Token, this.ForeignKeySchema, this.ForeignKeyTable, this.ForeignKeyColumn) : this.Token.ToString();
        }
    }
}